package com.lli.mc.converter.openoffice;

import java.io.File;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.DocumentFormatRegistry;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import com.lli.mc.conf.OpenOfficeConfig;
import com.lli.mc.untils.FileUtil;

@Service
public class OpenOfficeConverter {
    private static final Logger log = LoggerFactory
            .getLogger(OpenOfficeConverter.class);
    private static final DocumentFormatRegistry factory = new MyDocumentFormatRegistry();
    @Resource
    OpenOfficeConfig openOfficeConfig;
    @Resource
    OpenOfficeConnectionPool pool;

    public void convert(File sourceFile, File targetFile) {
        log.info("文档转换开始!");
        long start = System.currentTimeMillis();
        OpenOfficeConnection connection = null;
        try {
            // 1: 打开连接
            connection = pool.POOL.borrowObject();
            log.info(Thread.currentThread().getName() + "---" + connection);
            // 备注 StreamOpenOfficeDocumentConverter 没有 OpenOfficeDocumentConverter 快，但是OpenOfficeDocumentConverter需要
            // 与openoffice在一台电脑，而StreamOpenOfficeDocumentConverter可以远程访问
            // DocumentConverter converter = new OpenOfficeDocumentConverter(
            // connection);
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(
                    connection);
            // 2:获取Format
            DocumentFormat inputDocumentFormat = factory
                    .getFormatByFileExtension(FileUtil
                            .getExtensionName(sourceFile.getAbsolutePath()));
            DocumentFormat outputDocumentFormat = factory
                    .getFormatByFileExtension(FileUtil
                            .getExtensionName(targetFile.getAbsolutePath()));
            // 3:执行转换
            converter.convert(sourceFile, inputDocumentFormat, targetFile,
                    outputDocumentFormat);
        } catch (Exception e) {
            log.error("文档转换PDF失败", e);
        } finally {
            if (connection != null) {
                pool.POOL.returnObject(connection);
            }

        }
        log.info("文档转换结束！原始文件：{}，转换后文件：{}，耗时：{}ms", sourceFile.getPath(),
                targetFile.getPath(), System.currentTimeMillis() - start);
    }

}